package com.rz.htk.product.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rz.core.exception.GlobalException;
import com.rz.htk.dubbo.service.AdminService;
import com.rz.htk.dubbo.service.DictDataService;
import com.rz.htk.print.entity.PrintTemplate;
import com.rz.htk.print.service.IPrintTemplateService;
import com.rz.htk.product.entity.Product;
import com.rz.htk.product.entity.ProductPrice;
import com.rz.htk.product.entity.vo.PrdDeleteParam;
import com.rz.htk.product.mapper.ProductMapper;
import com.rz.htk.product.mapper.ProductPriceMapper;
import com.rz.htk.product.service.IProductPriceService;
import com.rz.htk.product.service.IProductService;
import com.rz.htk.serviceprovider.entity.ServiceProvider;
import com.rz.htk.serviceprovider.service.IServiceProviderService;
import consumer.model.Admin;
import consumer.model.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName ProductServiceImpl
 * @Description 产品service实现类
 * @Author maweiyue
 * @Date 2019/3/26 20:37
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Resource private DictDataService dictDataService;

    @Resource private IProductPriceService productPriceService;

    @Resource private IPrintTemplateService printTemplateService;

    @Resource private IServiceProviderService providerService;

    @Resource private ProductPriceMapper productPriceMapper;

    @Override
    public List<Product> listAll() {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0);
        return list(queryWrapper);
    }

    @Override
    public IPage<Product> getPage(Product product) {
        QueryWrapper<Product> wrapper = new QueryWrapper();
        wrapper.eq("del_flag",0);
        if (StringUtils.isNotEmpty(product.getPrdName())) {
            wrapper.like("prd_name", product.getPrdName());
        }
        if (StringUtils.isNotEmpty(product.getExpressCode())) {
            wrapper.like("express_code", product.getExpressCode());
        }

        Page<Product> page = new Page<>(product.getPageNo(), product.getPageSize());
        IPage<Product> desktopIPage = page(page, wrapper);
        buildResult(desktopIPage.getRecords());
        return desktopIPage;
    }

    private void buildResult(List<Product> records) {
        List<String> serviceProviderIds = new ArrayList<>();
        records.forEach(item->{
            serviceProviderIds.add(item.getExpressCode());
            SysDictData dictData = dictDataService.getByCode("unit_"+item.getUnit());
            if(dictData!=null){
                item.setUnitName(dictData.getDictdataName());
            }
        });
        Collection<ServiceProvider> serviceProviderList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(serviceProviderIds)) {
            serviceProviderList = providerService.listByIds(serviceProviderIds);
        }
        for (Product product : records){
            for (ServiceProvider provider : serviceProviderList) {
                if (product.getExpressCode().equals(provider.getId().toString())) {
                    product.setExpressServiceProvider(provider.getName());
                }
            }
        }
    }

    @Override
    @Transactional
    public boolean saveProduct(Product product){
        boolean isOk = false;
        if (product.getId() == null) {
            if (CollectionUtils.isNotEmpty(listProductByName(product.getPrdName()))) {
                throw new GlobalException("产品名称【" + product.getPrdName() + "】已存在！");
            }
            product.setDelFlag(0);
            product.setCrteTime(LocalDateTime.now());
            isOk = this.save(product);
            String id = product.getId().toString();
            int len = id.length();
            if (len < 4) {
                for (int i = 0; i < (4 - len); i++) {
                    id = "0" + id;
                }
            }
            product.setPrdCode("HTK_P" + id);
        } else {
            List<Product> oldProductList = listProductByName(product.getPrdName());
            if (CollectionUtils.isNotEmpty(oldProductList) && !product.getId().equals(oldProductList.get(0).getId())) {
                throw new GlobalException("产品名称【" + product.getPrdName() + "】已存在！");
            }
        }
        isOk = this.saveOrUpdate(product);
        if (!isOk) {
            throw new GlobalException("产品信息保存失败！");
        }
        return isOk;
    }

    @Override
    @Transactional
    public boolean batchDelete(PrdDeleteParam prdDeleteParam){
        prdDeleteParam.getIds().forEach(id -> {
            Product product = this.getById(id);
            if (product != null) {
                product.setDelFlag(1);
                boolean isOk = this.saveOrUpdate(product);
                if (isOk) {
                    List<ProductPrice> list = this.productPriceService.listProductPriceByPrdcode(product.getPrdCode());
                    for (ProductPrice price : list) {
                        price.setDelFlag(1);
                        this.productPriceService.saveOrUpdate(price);
                    }
                } else {
                    throw new GlobalException("产品信息【" + product.getPrdName() + "】删除失败！");
                }
            } else {
                throw new GlobalException("产品信息不存在，删除失败！");
            }
        });
        return true;
    }

    /**
     * 根据产品名称获取产品列表
     * @param prdName
     * @return
     */
    @Override
    public List<Product> listProductByName(String prdName) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("prd_name", prdName);
        queryWrapper.eq("del_flag", 0);
        return list(queryWrapper);
    }

    /**
     * 根据产品编号获取产品列表
     * @param prdCode
     * @return
     */
    @Override
    public Product getProductByCode(String prdCode) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("prd_code", prdCode);
        queryWrapper.eq("del_flag", 0);
        List<Product> list = list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据产品编号获取产品列表
     * @param prdCodes 产品编号集合
     * @return
     */
    @Override
    public List<Product> listProductByCodes(List<String> prdCodes) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("prd_code", prdCodes);
        queryWrapper.eq("del_flag", 0);
        return list(queryWrapper);
    }

    /**
     * 获取所有产品信息列表，包括每个产品的资费信息列表
     * @return
     */
    @Override
    public List<Product> listAllProduct(){
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        List<Product> productList = list(queryWrapper);
        productList.forEach(product -> {
            product.setProductPriceList(this.productPriceService.listProductPriceByPrdcode(product.getPrdCode()));
        });
        return productList;
    }

    /**
     * 获取产品详情下拉列表（产品-产品资费）
     * @return
     */
    @Override
    public JSONArray selectProductDtails() {
        List<Product> list = this.listAllProduct();
        JSONArray array = new JSONArray();
        list.forEach(product -> {
            List<ProductPrice> priceList = product.getProductPriceList();
            priceList.forEach(productPrice -> {
                array.add(this.createSelectProductDetails(product, productPrice));
            });
        });
        return array;
    }

    /**
     * 获取产品下拉列表
     * @return
     */
    public JSONArray selectAllProduct(){
        JSONArray array = new JSONArray();
        List<Product> list = this.listAllProduct();
        for (Product product : list) {
            JSONObject obj = new JSONObject();
            obj.put("prdCode", product.getPrdCode());
            obj.put("prdName", product.getPrdName());
            array.add(obj);
        }
        return array;
    }

    /**
     * 根据国家代码获取产品详情下拉列表
     * @param code 国家代码
     * @return
     */
    @Override
    public JSONArray selectProductDtailsByCountry(String code) {
        List<ProductPrice> list = this.productPriceService.listProductPriceByCountry(code);
        List<String> prdCodeList = new ArrayList<>();
        list.forEach(productPrice -> {
            prdCodeList.add(productPrice.getPrdCode());
        });
        JSONArray array = new JSONArray();
        if(prdCodeList.size()==0){
            return array;
        }
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        queryWrapper.in("prd_code", prdCodeList);
        List<Product> productList = list(queryWrapper);

        productList.forEach(product -> {
            list.forEach(productPrice -> {
                if (product.getPrdCode().equals(productPrice.getPrdCode())) {

                    array.add(this.createSelectProductDetails(product, productPrice));
                }
            });
        });
        return array;
    }

    private JSONObject createSelectProductDetails(Product product, ProductPrice productPrice){
        JSONObject obj = new JSONObject();
        obj.put("prdId", productPrice.getId());
        obj.put("prdName", this.productPriceService.getProductPriceName(product, productPrice));
        return obj;
    }

    @Override
    public PrintTemplate getTemplateByPrdId(Integer prdId) {
        Product product = getById(prdId);
        if(product!=null){
            Integer tempId = product.getExpressTemplate();
            return printTemplateService.getById(tempId);
        }
        return null;
    }

    public List<Product> listProductByCountry(String country){
        List<String> prdCodeList = productPriceMapper.selectDistinctPrdCode(country);
        if (CollectionUtils.isNotEmpty(prdCodeList)) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("del_flag", 0);
            queryWrapper.in("prd_code", prdCodeList);
            return list(queryWrapper);
        }
        return new ArrayList<>();
    }
}
